<?php
/**
 * // +----------------------------------------------------------------------
 * //            -------------------------
 * //           /   / ------------------\  \
 * //                                          \  \
 * //                                           /  /
 * //          /  /  ------------------- /  /
 * //        /  /  ----------------------
 * //      /  /
 * //      \  \
 * //        \  \  ------------------ /  /
 * //          \  \--------------------/
 * // +----------------------------------------------------------------------
 * // | Copyright (c) 2016 Sage  All rights reserved.
 * // +----------------------------------------------------------------------
 * // | Author: Sage
 * // +----------------------------------------------------------------------
 *
 */

/**
 * Created by PhpStorm.
 * User: Sage
 * Date: 2018/6/7
 * Time: 18:04
 */

namespace KysbsUtils\Service;

class ImageService {

    /**
     * 图片压缩-重新设置分辨率大小
     * @param     $src
     * @param     $dst,保存后的路径文件名
     * @param     $width,
     * @param     $height
     * @param int $crop,true:裁剪,false:按比例缩放
     *
     * @return bool|string
     */
    function imageCompress($src, $dst, $width, $height, $crop=true){
        if(!list($w, $h) = getimagesize($src)) return "errorUnsupported picture type!";
        $finfo = finfo_open(FILEINFO_MIME_TYPE);
        //$mime = finfo_file($finfo, dirname(__FILE__)."/".$filename);

        $mime = finfo_file($finfo, $src);
        //直接读取MIME类型来判断
        switch($mime){
            case 'image/bmp': $type = 'bmp'; break;
            case 'image/gif': $type = 'gif'; break;
            case 'image/jpeg':$type = 'jpg'; break;
            case 'image/png': $type = 'png'; break;
            default : return "errorUnsupported $mime picture type!";
        }
        //根据文件后缀判断类型，废弃
        //        $type = strtolower(substr(strrchr($src,"."),1));
        //        if($type == 'jpeg') $type = 'jpg';
        switch($type){
            case 'bmp': $img = imagecreatefromwbmp($src); break;
            case 'gif': $img = imagecreatefromgif($src); break;
            case 'jpg': $img = imagecreatefromjpeg($src); break;
            case 'png': $img = imagecreatefrompng($src); break;
            default : return "errorUnsupported $type picture type!";
        }

        // resize
        if($crop){
            //裁剪
            if($w < $width or $h < $height) return $src;
            $ratio = max($width/$w, $height/$h);
            $h = $height / $ratio;
            $x = ($w - $width / $ratio) / 2;
            $w = $width / $ratio;
        }
        else{
            //等比例缩小
            if($w < $width and $h < $height) return $src;
            $ratio = min($width/$w, $height/$h);
            $width = $w * $ratio;
            $height = $h * $ratio;
            $x = 0;
        }
        $new = imagecreatetruecolor($width, $height);
        // preserve transparency
        if($type == "gif" or $type == "png"){
            imagecolortransparent($new, imagecolorallocatealpha($new, 0, 0, 0, 127));
            imagealphablending($new, false);
            imagesavealpha($new, true);
        }
        imagecopyresampled($new, $img, 0, 0, $x, 0, $width, $height, $w, $h);
        switch($type){
            case 'bmp': imagewbmp($new, $dst); break;
            case 'gif': imagegif($new, $dst); break;
            case 'jpg': imagejpeg($new, $dst); break;
            case 'png': imagepng($new, $dst); break;
        }
        unlink($src);
        return $dst;
    }

    /**
     * 图片压缩-压缩到特定文件大小
     * @param     $src,原文件位置
     * @param     $dst,压缩后存放文件名
     * @param int $compressSize,压缩到多大物理内存
     *
     * @return string
     */
    function CompressByImgSize($src,$dst,$compressSize=819200){
        if(!list($w, $h) = getimagesize($src)) return "errorUnsupported picture type!";
        // resize
        $fileSize=filesize($src); //文件大小，字节
        if($fileSize<$compressSize){
            return $src;
        }
        $finfo = finfo_open(FILEINFO_MIME_TYPE);
        //$mime = finfo_file($finfo, dirname(__FILE__)."/".$filename);

        $mime = finfo_file($finfo, $src);
        //直接读取MIME类型来判断
        switch($mime){
            case 'image/bmp': $type = 'bmp'; break;
            case 'image/gif': $type = 'gif'; break;
            case 'image/jpeg':$type = 'jpg'; break;
            case 'image/png': $type = 'png'; break;
            default : return "errorUnsupported $mime picture type!";
        }
        switch($type){
            case 'bmp': $img = imagecreatefromwbmp($src); break;
            case 'gif': $img = imagecreatefromgif($src); break;
            case 'jpg': $img = imagecreatefromjpeg($src); break;
            case 'png': $img = imagecreatefrompng($src); break;
            default : return "errorUnsupported $type picture type!";
        }


        //        dump($fileSize);
        //        dump($fileSize);
        //        $ratio=number_format(sqrt($compressSize/$fileSize),2);
        $ratio=number_format($compressSize/$fileSize,2);
        if($ratio<=0) return $src;
        if($ratio>1){
            $ratio=1;
        }
        $w_new=(int)($w*$ratio);
        $h_new=(int)($h*$ratio);

        //        dump($w);
        //        dump($h);
        //        dump($ratio);
        //        dump($width);
        //        dump($height);
        //        exit();
        $new = imagecreatetruecolor($w_new, $h_new);
        // preserve transparency
        if($type == "gif" or $type == "png"){
            imagecolortransparent($new, imagecolorallocatealpha($new, 0, 0, 0, 127));
            imagealphablending($new, true);
            imagesavealpha($new, false);
        }
        imagecopyresampled($new, $img, 0, 0, 0, 0, $w_new, $h_new, $w, $h);
        switch($type){
            case 'bmp1':
                imagewbmp($new, $dst);
                break;
            case 'gif':
                imagegif($new, $dst);
                break;
            case 'jpg':
                imagejpeg($new, $dst,40);
                break;
            case 'png1':
                imagepng($new, $dst);
                break;
            default:
                imagejpeg($new, $dst,40);
                break;
        }
        imagedestroy($new);
        unlink($src);
        return $dst;
    }
}